package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;

import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.mapper.SysQuestionDomainMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysQuestionDomain;
import com.ruoyi.system.service.ISysQuestionDomainService;

/**
 * 问题领域Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-05-07
 */
@Service
public class SysQuestionDomainServiceImpl implements ISysQuestionDomainService 
{
    @Autowired
    private SysQuestionDomainMapper sysQuestionDomainMapper;


    /**
     * 查询部门管理数据
     *
     * @param domain 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(questionDomainAlias = "f")
    public List<SysQuestionDomain> selectQuestionDomainList(SysQuestionDomain domain)
    {
        return sysQuestionDomainMapper.selectQuestionDomainList(domain);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param domains 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysQuestionDomain> buildQuestionDomainTree(List<SysQuestionDomain> domains)
    {
        List<SysQuestionDomain> returnList = new ArrayList<SysQuestionDomain>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysQuestionDomain domain : domains)
        {
            tempList.add(domain.getDomainId());
        }
        for (SysQuestionDomain domain : domains)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(domain.getParentId()))
            {
                recursionFn(domains, domain);
                returnList.add(domain);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = domains;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param domains 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildQuestionDomainTreeSelect(List<SysQuestionDomain> domains)
    {
        List<SysQuestionDomain> domainTrees = buildQuestionDomainTree(domains);
        return domainTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }



    /**
     * 根据部门ID查询信息
     *
     * @param domainId 部门ID
     * @return 部门信息
     */
    @Override
    public SysQuestionDomain selectQuestionDomainById(Long domainId)
    {
        return sysQuestionDomainMapper.selectQuestionDomainById(domainId);
    }



    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param domainId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenQuestionDomainById(Long domainId)
    {
        return sysQuestionDomainMapper.selectNormalChildrenQuestionDomainById(domainId);
    }

    /**
     * 是否存在子节点
     *
     * @param domainId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByQuestionDomainById(Long domainId)
    {
        int result = sysQuestionDomainMapper.hasChildByQuestionDomainById(domainId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param domainId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkQuestionDomainExistQuestion(Long domainId)
    {
        return false;
//
//        int result = sysQuestionDomainMapper.checkQuestionDomainExistQuestion(domainId);
//        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param domain 部门信息
     * @return 结果
     */
    @Override
    public String checkQuestionDomainNameUnique(SysQuestionDomain domain)
    {
        Long domainId = StringUtils.isNull(domain.getDomainId()) ? -1L : domain.getDomainId();
        SysQuestionDomain info = sysQuestionDomainMapper.checkQuestionDomainNameUnique(domain.getDomainName(), domain.getParentId());
        if (StringUtils.isNotNull(info) && info.getDomainId().longValue() != domainId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param domainId 部门id
     */
    @Override
    public void checkQuestionDomainDataScope(Long domainId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysQuestionDomain domain = new SysQuestionDomain();
            domain.setDomainId(domainId);
            List<SysQuestionDomain> domains = SpringUtils.getAopProxy(this).selectQuestionDomainList(domain);
            if (StringUtils.isEmpty(domains))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param domain 部门信息
     * @return 结果
     */
    @Override
    public int insertQuestionDomain(SysQuestionDomain domain)
    {
        SysQuestionDomain info = sysQuestionDomainMapper.selectQuestionDomainById(domain.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        domain.setAncestors(info.getAncestors() + "," + domain.getParentId());
        return sysQuestionDomainMapper.insertQuestionDomain(domain);
    }

    @Override
    public int inserRootDomain(SysQuestionDomain domain) {
        return sysQuestionDomainMapper.insertQuestionDomain(domain);
    }



    /**
     * 修改保存部门信息
     *
     * @param domain 部门信息
     * @return 结果
     */
    @Override
    public int updateQuestionDomain(SysQuestionDomain domain)
    {
        SysQuestionDomain newParentQuestionDomain = sysQuestionDomainMapper.selectQuestionDomainById(domain.getParentId());
        SysQuestionDomain oldQuestionDomain = sysQuestionDomainMapper.selectQuestionDomainById(domain.getDomainId());
        if (StringUtils.isNotNull(newParentQuestionDomain) && StringUtils.isNotNull(oldQuestionDomain))
        {
            String newAncestors = newParentQuestionDomain.getAncestors() + "," + newParentQuestionDomain.getDomainId();
            String oldAncestors = oldQuestionDomain.getAncestors();
            domain.setAncestors(newAncestors);
            updateQuestionDomainChildren(domain.getDomainId(), newAncestors, oldAncestors);
        }
        int result = sysQuestionDomainMapper.updateQuestionDomain(domain);
        if (UserConstants.DEPT_NORMAL.equals(domain.getStatus()) && StringUtils.isNotEmpty(domain.getAncestors())
                && !StringUtils.equals("0", domain.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentQuestionDomainStatusNormal(domain);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param domain 当前部门
     */
    private void updateParentQuestionDomainStatusNormal(SysQuestionDomain domain)
    {
        String ancestors = domain.getAncestors();
        Long[] domainIds = Convert.toLongArray(ancestors);
        sysQuestionDomainMapper.updateQuestionDomainStatusNormal(domainIds);
    }

    /**
     * 修改子元素关系
     *
     * @param domainId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateQuestionDomainChildren(Long domainId, String newAncestors, String oldAncestors)
    {
        List<SysQuestionDomain> children = sysQuestionDomainMapper.selectChildrenQuestionDomainById(domainId);
        for (SysQuestionDomain child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            sysQuestionDomainMapper.updateQuestionDomainChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param domainId 部门ID
     * @return 结果
     */
    @Override
    public int deleteQuestionDomainById(Long domainId)
    {
        return sysQuestionDomainMapper.deleteQuestionDomainById(domainId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysQuestionDomain> list, SysQuestionDomain t)
    {
        // 得到子节点列表
        List<SysQuestionDomain> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysQuestionDomain tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysQuestionDomain> getChildList(List<SysQuestionDomain> list, SysQuestionDomain t)
    {
        List<SysQuestionDomain> tlist = new ArrayList<SysQuestionDomain>();
        Iterator<SysQuestionDomain> it = list.iterator();
        while (it.hasNext())
        {
            SysQuestionDomain n = (SysQuestionDomain) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDomainId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysQuestionDomain> list, SysQuestionDomain t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public List<SysQuestionDomain> selectQuestionDomainListByIds(Set<Long> domainIds) {
        return sysQuestionDomainMapper.selectQuestionDomainListByIds(domainIds);
    }
}
